package dominia.widgets;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import dominia.SWTMain;

/**
 * A singleton dialog that receives connection parameters such as server address,
 * username and password from the user.
 * 
 * @author jfb
 *
 */
public class ConnectDialog extends SingletonDialog {

	protected ConnectDialog()
	{
		super("Connect to server");
	}

	public static ConnectDialog getInstance()
	{
		return (ConnectDialog)SingletonDialog.getInstance(ConnectDialog.class);
	}
	
	public void show()
	{
		final Display display = SWTMain.getDisplay();
		
		
		
		Shell parent = getParent();
		final Shell shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
		shell.setText("connecting");
		shell.setSize(300, 150);
		
		GridLayout layout = new GridLayout();
		layout.marginLeft = 10;
		layout.marginTop = 10;
		layout.numColumns = 2;
		shell.setLayout(layout);

		final int[] count = new int[] { 50 };
		final ProgressBar bar = new ProgressBar(shell, SWT.SMOOTH);
		bar.setMaximum(count[0]);
		GridData progressData = new GridData();
		bar.setLayoutData(progressData);
		
		GridData gd = new GridData();
		Label connectingLabel = new Label(shell, SWT.LEFT);
		connectingLabel.setText("Connecting...");
		connectingLabel.setLayoutData(gd);

		final Runnable check = new Runnable() {
			public void run() {
				for (int i = 0; i < count[0]; i++) {
					bar.setSelection(i + 1);
					/*if(i+1 == count[0]) {
						i = 0;
					}*/
					if(SWTMain.isConnected()) {
						break;
					}
					
					try {
						Thread.sleep(100);
					} catch (Throwable e) {
					}
				}
				
				shell.close();
				shell.dispose();
			}
		};
		
		Button cancelBtn = new Button(shell, SWT.CENTER);
		cancelBtn.setText("Cancel");
		gd = new GridData();
		cancelBtn.setLayoutData(gd);
		cancelBtn.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(MouseEvent arg0) {}
			public void mouseDown(MouseEvent arg0) {
				display.disposeExec(check);
				shell.close();
			}
			public void mouseUp(MouseEvent arg0) {}
		});
		shell.pack();
		shell.open();
		
		
		display.asyncExec(check);
		/*Display display = parent.getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		return result;*/
	}
}